package luongvd.weather.control;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import luongvd.weather.R;
import luongvd.weather.common.Const;
import luongvd.weather.common.Utils;
import luongvd.weather.common.service.utils.NetworkUtil;
import luongvd.weather.model.adapter.AdapterWeatherCity;
import luongvd.weather.model.dbhelper.DatabaseHandler;
import luongvd.weather.model.delegate.ServiceDelegate;
import luongvd.weather.model.entity.EntityWeather;
import luongvd.weather.model.object.ObjectCity;
import luongvd.weather.model.object.ObjectForecast;
import luongvd.weather.model.object.ObjectWeather;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

@SuppressLint("SimpleDateFormat")
public class AddCityActivity extends Activity implements OnClickListener{
	LinearLayout ln_back;
	ImageButton ib_add, ib_update;
	ProgressBar progressBarLoadding;
	ListView list_city;
	TextView tv_time_update;
	
	String lat, lon;
	long dt_default;
	ProgressDialog dialogLoading;
	ObjectWeather objectWeather;
	ObjectForecast objectForecast;
	ArrayList<ObjectWeather> arrayWeather;
	AdapterWeatherCity adapter;
	int REQUEST_CODE = 1;
	ObjectCity objectCity;
	String date_update;
	ArrayList<ObjectForecast> arrayForecast;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_city);
        unitDB();
        unitWidget();
        setDB();
    }
	
	private void setDB() {
//		if(date_update == null)
//		{
//			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//			date_update = sdf.format(new Date());
//		}
//		tv_time_update.setText(date_update);
		
		adapter.notifyDataSetChanged();
	}

	private void clearLoadingDialog(Boolean setDateUpdate){
		dialogLoading.dismiss();
		ib_update.setVisibility(View.VISIBLE);
		progressBarLoadding.setVisibility(View.GONE);
		if(setDateUpdate == true)
		{
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
			String currentDateandTime = sdf.format(new Date());
			tv_time_update.setText(currentDateandTime);
		}
	}
	
	private void setUnitWidget() {
		if(NetworkUtil.checkNetWork(this))
		{
			dialogLoading = ProgressDialog.show(this, "", getString(R.string.loading_please_wait_), true);
			ib_update.setVisibility(View.GONE);
			progressBarLoadding.setVisibility(View.VISIBLE);
			ServiceDelegate.getWeather(lat, lon, getWeatherHandler);
		}else{
			Toast.makeText(getBaseContext(), getString(R.string.internet_not_connect_), Toast.LENGTH_SHORT).show();
		}
	}
	
	Handler getWeatherHandler = new Handler() {
		@SuppressLint("SimpleDateFormat") public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject json = new JSONObject();
					json = (JSONObject) msg.obj;
					if(json!=null)
					{
						Log.d("Luong", "---------------json: "+json);
						int cod = json.getInt(Const.KEY_COD);
						Log.d("Luong", "---------------cod: "+cod);
						if(cod == 200)
						{
							long dt = json.getLong(Const.KEY_TIME_UPDATE);
							Log.d("Luong", "------------- dt: "+dt);
							if(dt != dt_default)
							{
								dt_default = dt;
								objectWeather = new ObjectWeather();
								
								String name_city = json.getString(Const.KEY_NAME_CITY);
								Log.d("Luong", "------------- name city: "+name_city);
								objectWeather.setName_city(name_city);
								
								objectWeather.setDt_weather(String.valueOf(dt));
								String date_city = Utils.convertUnixtimeToTime(dt);
								Log.d("Luong", "------------- date_city: "+date_city);
								objectWeather.setDate_city(date_city);
								
								JSONObject weather = new JSONObject();
								weather = json.getJSONArray(Const.KEY_WEATHER).getJSONObject(0);
								
								String id_weather = weather.getString(Const.KEY_ID_WEATHER);
								Log.d("Luong", "------------- id_weather: "+id_weather);
								objectWeather.setId_weather(id_weather);
								
								String icon_weather = weather.getString(Const.KEY_ICON_WEATHER);
								Log.d("Luong", "------------- icon_weather: "+icon_weather);
								objectWeather.setIcon_weather(icon_weather);
								
								String description_weather = weather.getString(Const.KEY_DESCRIPTION);
								Log.d("Luong", "------------- description_weather: "+description_weather);
								objectWeather.setDescription_weather(description_weather);
								
								JSONObject main = json.getJSONObject(Const.KEY_MAIN);
								
								String temp = String.valueOf(Math.round(main.getDouble(Const.KEY_TEMP)));
								Log.d("Luong", "------------- temp: "+temp);
								objectWeather.setTemp(temp);
								
								String temp_max = String.valueOf(Math.round(main.getDouble(Const.KEY_TEMP_MAX)));
								Log.d("Luong", "------------- temp_max: "+temp_max);
								objectWeather.setTemp_max(temp_max);
								
								String temp_min = String.valueOf(Math.round(main.getDouble(Const.KEY_TEMP_MIN)));
								Log.d("Luong", "------------- temp_min: "+temp_min);
								objectWeather.setTemp_min(temp_min);
								
								String humidity = main.getString(Const.KEY_HUMIDITY);
								Log.d("Luong", "------------- humidity: "+humidity);
								objectWeather.setHumidity(humidity);
								
								arrayWeather.add(objectWeather);
								setDB();
								if(NetworkUtil.checkNetWork(AddCityActivity.this))
								{
									ServiceDelegate.getForecast(lat, lon, getForecastHandler);
								}
							}else{
								clearLoadingDialog(true);
							}
						}else{
							clearLoadingDialog(false);
							Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
						}
					}else{
						clearLoadingDialog(false);
						Log.d("Luong", "------------Json is null");
						Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
					}
				}catch(Exception e)
				{
					
				}
			}else if (msg.arg1 == -1) {
				clearLoadingDialog(false);
				Log.d("Luong", "------------not connect to server");
				Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
			}
		}

	};
	
	Handler getForecastHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject json = new JSONObject();
					json = (JSONObject) msg.obj;
					if(json!=null)
					{
						Log.d("Luong", "===================== json: "+json);
						int cod = json.getInt(Const.KEY_COD);
						Log.d("Luong", "===================== cod: "+cod);
						if(cod == 200)
						{
							arrayForecast = new ArrayList<ObjectForecast>();
							
							JSONArray jsonListForecast = json.getJSONArray(Const.KEY_LIST);
							Log.d("Luong", "===================== jsonListForecast size: "+jsonListForecast.length());
							
							for(int i=1; i< jsonListForecast.length(); i++)
							{
								objectForecast = new ObjectForecast();
								JSONObject jsonObjectForecast = jsonListForecast.getJSONObject(i);
								long dt = jsonObjectForecast.getLong(Const.KEY_TIME_UPDATE);
								objectForecast.setDt_forecast(String.valueOf(dt));
								Log.d("Luong", "===================== dt: "+dt);
								
								String day_of_week = Utils.convertUnixtimeToDayOfWeek(dt);
								objectForecast.setDay_of_week(day_of_week);
								Log.d("Luong", "===================== day_of_week: "+day_of_week);
								
								String day_of_month = Utils.convertUnixtimeToDayOfMonth(dt);
								objectForecast.setDay_of_month(day_of_month);
								Log.d("Luong", "===================== day_of_month: "+day_of_month);
								
								JSONObject temp = jsonObjectForecast.getJSONObject(Const.KEY_TEMP);
								String temp_max = String.valueOf(Math.round(temp.getDouble(Const.KEY_MAX)));
								objectForecast.setTemp_max(temp_max);
								Log.d("Luong", "===================== temp_max: "+temp_max);
								
								String temp_min = String.valueOf(Math.round(temp.getDouble(Const.KEY_MIN)));
								objectForecast.setTemp_min(temp_min);
								Log.d("Luong", "===================== temp_min: "+temp_min);
								
								JSONObject weather = jsonObjectForecast.getJSONArray(Const.KEY_WEATHER).getJSONObject(0);
								String icon = weather.getString(Const.KEY_ICON_WEATHER);
								objectForecast.setIcon(icon);
								Log.d("Luong", "===================== icon: "+icon);
								
								String id_weather = weather.getString(Const.KEY_ID_WEATHER);
								objectForecast.setId_weather(id_weather);
								Log.d("Luong", "===================== id_weather: "+id_weather);
								
								arrayForecast.add(objectForecast);
							}
							clearLoadingDialog(true);
							saveDBClient();
						}else{
							clearLoadingDialog(false);
							Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
						}
					}else{
						clearLoadingDialog(false);
						Log.d("Luong", "===================== Json is null");
						Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
					}
				}catch(Exception e)
				{
					
				}
			}else if (msg.arg1 == -1) {
				clearLoadingDialog(false);
				Log.d("Luong", "===================== not connect to server");
				Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	private void saveDBClient(){
		//save to db client
//		DatabaseHandler.deleteRowWeatherByName(objectWeather.getName_city());
//		DatabaseHandler.deleteRowForecastByName(objectWeather.getName_city());
//		DatabaseHandler.deleteRowWeatherView();
//		DatabaseHandler.addWeatherView(objectWeather.getName_city(),tv_time_update.getText().toString());
		DatabaseHandler.addWeather(objectWeather.getDt_weather(), objectWeather.getDate_city(), objectWeather.getName_city(), objectWeather.getIcon_weather(), objectWeather.getTemp(), objectWeather.getTemp_max(), objectWeather.getTemp_min(), objectWeather.getHumidity(), objectWeather.getDescription_weather());
		Log.d("Luong", "========================== size arrayForecast insert:"+arrayForecast.size());
		for(int i=0; i< arrayForecast.size(); i++)
		{
			ObjectForecast objectForcast = arrayForecast.get(i);
			DatabaseHandler.addForecast(objectWeather.getDt_weather(), objectWeather.getName_city(), objectForcast.getDay_of_week(), objectForcast.getDay_of_month(), objectForcast.getIcon(), objectForcast.getTemp_max(), objectForcast.getTemp_min());
		}
	}

	
	private void unitWidget() {
		ln_back = (LinearLayout)findViewById(R.id.ln_back);
		ln_back.setOnClickListener(this);
		ib_add = (ImageButton)findViewById(R.id.ib_add);
		ib_add.setOnClickListener(this);
		ib_update = (ImageButton)findViewById(R.id.ib_update);
		ib_update.setOnClickListener(this);
		progressBarLoadding = (ProgressBar)findViewById(R.id.progressBarLoadding);
		list_city = (ListView)findViewById(R.id.list_city);
		tv_time_update = (TextView)findViewById(R.id.tv_time_update);
		adapter = new AdapterWeatherCity(this, arrayWeather);
		list_city.setAdapter(adapter);
	}

	private void unitDB() {
//		Intent intent = new Intent();
//		intent = getIntent();
//		String json_weather = intent.getExtras().getString(Const.KEY_JSON_WEATHER);
//		Log.d("Luong", "================== json_weather: "+json_weather);
//		//convert json to object
//		Gson gson = new Gson();
//		objectWeather = gson.fromJson(json_weather, ObjectWeather.class);
//		
//		Log.d("Luong", "================== objectWeather name: "+objectWeather.getName_city());
//		
//		dt_default = intent.getExtras().getLong(Const.KEY_TIME_UPDATE);
//		Log.d("Luong", "================== dt_default: "+dt_default);
//		lat = intent.getExtras().getString(Const.KEY_LAT);
//		Log.d("Luong", "================== lat: "+lat);
//		lon = intent.getExtras().getString(Const.KEY_LON);
//		Log.d("Luong", "================== lon: "+lon);
		
		arrayWeather = new ArrayList<ObjectWeather>();
		EntityWeather entityWeather = new EntityWeather(this);
		arrayWeather = entityWeather.getInfoWeatherAllLocation();
		
		objectCity = new ObjectCity();
		objectCity = entityWeather.getInfoWeatherView();
		
		if(objectCity.getTime_update() != null)
		{
			date_update = objectCity.getTime_update();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE) {
			if(resultCode == RESULT_OK){      
		         String json_city = data.getStringExtra(Const.KEY_JSON_CITY);    
		         Gson gson = new Gson();
		         objectCity = gson.fromJson(json_city, ObjectCity.class);
		         lat = objectCity.getLat();
		         lon = objectCity.getLon();
		         Log.d("Luong", "============== lat; "+lat);
		         Log.d("Luong", "============== lon; "+lon);
		         setUnitWidget();
		     }
		     if (resultCode == RESULT_CANCELED) {    
		         //Write your code if there's no result
		     }
		}
		
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ln_back:
			finish();
			break;
		case R.id.ib_add:
			Intent intent = new Intent(this, SearchCityActivity.class);
			startActivityForResult(intent, REQUEST_CODE);
			break;
		case R.id.ib_update:
			finish();
			break;

		default:
			break;
		}
		
	}

}
